package com.echoesnet.echoesshortvideo.Fragments;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.echoesnet.echoesshortvideo.Activities.BindPhoneAct;
import com.echoesnet.echoesshortvideo.Activities.ReportFoulsUserAct;
import com.echoesnet.echoesshortvideo.Api.ErrorCodeTable;
import com.echoesnet.echoesshortvideo.AppController;
import com.echoesnet.echoesshortvideo.Beans.IncludeNavBarBean;
import com.echoesnet.echoesshortvideo.Beans.ShareToFaceBean;
import com.echoesnet.echoesshortvideo.Beans.Video;
import com.echoesnet.echoesshortvideo.Constant.Api;
import com.echoesnet.echoesshortvideo.Constant.CommonConstant;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.Image.GlideApp;
import com.echoesnet.echoesshortvideo.Utils.NetUtil;
import com.echoesnet.echoesshortvideo.Utils.NetUtilListener;
import com.echoesnet.echoesshortvideo.Utils.SharePreUtils;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.Utils.VideoUtils;
import com.echoesnet.echoesshortvideo.ViewModels.VideoPlayViewModel;
import com.echoesnet.echoesshortvideo.databinding.VideoPlayBinding;
import com.echoesnet.echoesshortvideo.views.CommentListDialog;
import com.echoesnet.echoesshortvideo.views.InputTextMsgDialog;
import com.echoesnet.echoesshortvideo.views.LikeHeartLayout;
import com.echoesnet.echoesshortvideo.views.VerticalViewPager;
import com.echoesnet.echoesshortvideo.views.adapters.SharesAdapter;
import com.echoesnet.echoesshortvideo.views.dialog.CustomAlertDialog;
import com.echoesnet.echoesshortvideo.views.video.EmptyControlVideo;
import com.flipboard.bottomsheet.BottomSheetLayout;
import com.flipboard.bottomsheet.OnSheetDismissedListener;
import com.like.LikeButton;
import com.like.OnLikeListener;
import com.orhanobut.logger.Logger;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * @author yqh
 * @Date 2018/4/23
 * @Version 1.0
 */
public class VideoPlayFragment extends BaseFragment
{
    private final String TAG = VideoPlayFragment.class.getSimpleName();

    @BindView(R.id.tvNickName)
    TextView tvNickName;
    @BindView(R.id.tvSimpleIntroduce)
    TextView tvSimpleIntroduce;
    @BindView(R.id.ivHead)
    ImageView ivHead;
    @BindView(R.id.tvFocus)
    TextView tvFocus;
    @BindView(R.id.rlLove)
    RelativeLayout rlLove;
    @BindView(R.id.rlComments)
    RelativeLayout rlComments;
    @BindView(R.id.rlShare)
    RelativeLayout rlShare;
    @BindView(R.id.ll_bottom_lay)
    TextView llBottomLay;
    @BindView(R.id.bottomSheetLayout)
    BottomSheetLayout bottomSheetLayout;
    @BindView(R.id.playVideo)
    EmptyControlVideo playVideo;
    @BindView(R.id.tvLoveNum)
    TextView tvLoveNum;
    @BindView(R.id.tvCommentsNum)
    TextView tvCommentsNum;
    @BindView(R.id.tvShareText)
    TextView tvShareNum;
    @BindView(R.id.ivLove)
    LikeButton ivLove;
    @BindView(R.id.videoCover)
    ImageView videoCover;
    @BindView(R.id.btnPlay)
    ImageView btnPlay;
    @BindView(R.id.deleteVideo)
    ImageView deleteVideo;
    @BindView(R.id.likeHeartView)
    LikeHeartLayout likeHeartView;

    private Unbinder unbinder;
    private Activity mActivity;

    private String videoUrl;
    private Video videoInfo;

    private VideoPlayViewModel model;

    private String title;//Fragment标识

    private boolean isLiked;

    private VerticalViewPager parentVerticalViewPager;
    private InputTextMsgDialog dialog;

    private VideoPlayBinding binding;
    private IncludeNavBarBean navBean;

    private boolean isPrepared = false;
    private boolean isNeedPause = false;
    private boolean isReleased = false;

    private boolean isShow2User = false;


    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        binding = DataBindingUtil.inflate(inflater, R.layout.video_play, container, false);
        unbinder = ButterKnife.bind(this, binding.getRoot());
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        afterViews();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser)
    {
        super.setUserVisibleHint(isVisibleToUser);
        Logger.t(TAG).d("setUserVisibleHint():" + isVisibleToUser);
        isShow2User = isVisibleToUser;
        if (isVisibleToUser)
        {
            startPlayVideo();
        }
    }

    @Override
    public void onResume()
    {
        super.onResume();
        Logger.t(TAG).d(TAG + ":onResume()");
        if (AppController.getInstance().videoPlayPagePosition == 0)
            switchVideo(true);
    }

    @Override
    public void onPause()
    {
        super.onPause();
        Logger.t(TAG).d(TAG + ":onPause()");
    }

    @Override
    protected String getPageName()
    {
        return TAG;
    }

    private void afterViews()
    {
        mActivity = getActivity();

        navBean = new IncludeNavBarBean(false, true);
        binding.relNavBar.setNavBean(navBean);
        binding.relNavBar.itvLeft.setOnClickListener(view -> mActivity.finish());

        Bundle bundle = getArguments();
        if (bundle != null)
        {
            model = new VideoPlayViewModel();
            videoInfo = bundle.getParcelable("videoDetail");
            Logger.t(TAG).d("videoInfo:" + videoInfo);

            observerAction();

            registerBroReceiver();

            videoUrl = videoInfo.getUrl();

            setVideoPlay(videoUrl);

            //缩略图
            GlideApp.with(mActivity)
                    .load(videoInfo.getThumbnails())
                    .placeholder(R.color.transparent)
                    .into(videoCover);
            tvNickName.setText("@" + videoInfo.getNickName());
            tvSimpleIntroduce.setText(videoInfo.getContent());
            GlideApp.with(mActivity)
                    .load(videoInfo.getHeadPic())
                    .circleCrop()
                    .error(R.drawable.default_80px)
                    .into(ivHead);
            tvFocus.setVisibility("0".equals(videoInfo.getFollowOrNot()) ? View.VISIBLE : View.GONE);
            tvLoveNum.setText(videoInfo.getLikeNum());
            tvCommentsNum.setText(videoInfo.getCommentNum());
            tvShareNum.setText(videoInfo.getShareNum());
            //已点赞
            isLiked = "1".equals(videoInfo.getLikeOrNot());
            ivLove.setLiked(isLiked);

            if (SharePreUtils.getUId().equals(videoInfo.getUserId()))
                deleteVideo.setVisibility(View.VISIBLE);

//            int res = "1".equals(videoInfo.getLikeOrNot()) ? R.drawable.but_big_heart_activate : R.drawable.but_big_heart_default;
//            ivLove.setTag("1".equals(videoInfo.getLikeOrNot()));
//            ivLove.setImageResource(res);
            if (getArguments().getBoolean("autoPlay", false))
            {
                startPlayVideo();
                Intent intent = new Intent(CommonConstant.EAM_BRD_ACTION_REQUEST_USERINFO);
                String uid = videoInfo.getUserId();
                intent.putExtra("otherUserId", uid);
                mActivity.sendBroadcast(intent);
//                videoCover.setVisibility(View.GONE);
            }

            likeHeartView.setOnViewClickActionListener(new LikeHeartLayout.OnViewClickActionListener()
            {
                @Override
                public void onClick()
                {
                    IMediaPlayer iMediaPlayers = playVideo.getGSYVideoManager().getMediaPlayer();
                    if (iMediaPlayers != null)
                    {
                        if (iMediaPlayers.isPlaying())
                            switchVideo(false);
                        else
                            switchVideo(true);
                    }
                }

                @Override
                public void onDoubleClick()
                {
                    if (!ivLove.isLiked())
                    {
                        ivLove.performClick();
                    }
                }
            });


            bottomSheetLayout.setPeekSheetTranslation(CommonUtils.dp2px(mActivity, 250));

            bottomSheetLayout.addOnSheetDismissedListener(new OnSheetDismissedListener()
            {
                @Override
                public void onDismissed(BottomSheetLayout bottomSheetLayout)
                {
                    parentVerticalViewPager.setStopScroll(false);
                }
            });
            bottomSheetLayout.removeOnSheetStateChangeListener(new BottomSheetLayout.OnSheetStateChangeListener()
            {
                @Override
                public void onSheetStateChanged(BottomSheetLayout.State state)
                {

                }
            });
            ivLove.setOnLikeListener(new OnLikeListener()
            {
                @Override
                public void liked(LikeButton likeButton)
                {
                    if (CommonUtils.checkUserStateFromFragment(VideoPlayFragment.this, TAG))
                    {
                        isLiked = true;
                        if (videoInfo != null)
                            model.startLikeVideo(videoInfo.getVideoId());
                    }
                    else
                        ivLove.setLiked(false);
                }

                @Override
                public void unLiked(LikeButton likeButton)
                {
                    isLiked = false;
                    if (videoInfo != null)
                        model.startLikeVideo(videoInfo.getVideoId());
                }
            });
        }
    }

    private void setVideoPlay(String videoUrl)
    {
        playVideo.setShowPauseCover(false);
        playVideo.setUp(videoUrl, false, null);

        playVideo.setVideoAllCallBack(new GSYSampleCallBack()
        {
            @Override
            public void onPrepared(String url, Object... objects)
            {
                super.onPrepared(url, objects);
                Logger.t(TAG).d("video onPrepared()：");
                isPrepared = true;
                if (isNeedPause)
                {
                    IMediaPlayer iMediaPlayers = playVideo.getGSYVideoManager().getMediaPlayer();
                    if (iMediaPlayers != null)
                        iMediaPlayers.pause();
//                    playVideo.onVideoPause();
                    isNeedPause = false;
                }
                else
                    playVideo.onVideoResume();
            }

            @Override
            public void onAutoComplete(String url, Object... objects)
            {
                super.onAutoComplete(url, objects);
                playVideo.startPlayLogic();
            }
        });

    }

    private void startPlayVideo()
    {
        int net = NetUtil.getNetworkStatus(mActivity);
        Animation btnPlayAnim = null;
        if (mActivity != null)
        {
            btnPlayAnim = AnimationUtils.loadAnimation(mActivity, R.anim.video_play_anim);
        }
        if (AppController.getInstance().videoRefuseNetTip)
            net = 1;
        switch (net)
        {
            case 1:
                if (playVideo != null)
                    playVideo.startPlayLogic();
                if (btnPlayAnim != null)
                {
                    if (btnPlay != null)
                    {
                        if (btnPlay.getVisibility() == View.VISIBLE)
                        {
                            btnPlay.setVisibility(View.GONE);
                            btnPlay.setAnimation(btnPlayAnim);
                        }
                    }
                }
                break;
            case 2:
            case 3:
                Animation finalBtnPlayAnim = btnPlayAnim;
                if (mActivity == null)
                    return;
                new CustomAlertDialog(mActivity)
                        .builder()
                        .setCancelable(true)
                        .setMsg("当前网络环境为4G\n是否继续观看\n")
                        .setPositiveButton("继续", v ->
                        {
                            if (playVideo != null)
                                playVideo.startPlayLogic();
                            AppController.getInstance().videoRefuseNetTip = true;
                            if (finalBtnPlayAnim != null)
                            {
                                if (btnPlay != null)
                                {
                                    if (btnPlay.getVisibility() == View.VISIBLE)
                                    {
                                        btnPlay.setVisibility(View.GONE);
                                        btnPlay.setAnimation(finalBtnPlayAnim);
                                    }
                                }
                            }
                        })
                        .setNegativeButton("退出", v ->
                        {
                            mActivity.finish();
                        }).show();
                break;
        }
    }

    /**
     * 接口回调
     */
    private void observerAction()
    {
        model.getLikeData().observe(this, result -> {
            if (!TextUtils.isEmpty(result))
            {
                int likeNum = 0;
                try
                {
                    if (isLiked)
                    {
                        likeNum = Integer.parseInt(tvLoveNum.getText().toString()) + 1;
//                        ivLove.setLiked(false);
                    }
                    else
                    {
                        //暂时保留  产品让 只加 不减
//                        likeNum = Integer.parseInt(tvLoveNum.getText().toString()) - 1;
                        likeNum = Integer.parseInt(tvLoveNum.getText().toString());
//                        ivLove.setLiked(true);
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
                tvLoveNum.setText(String.valueOf(likeNum));
            }
        });
        model.getCommentDetail().observe(this, result -> {
            if (!TextUtils.isEmpty(result))
            {
                if (dialog != null)
                {
                    dialog.dismiss();
                    ToastUtils.showShort("评论成功");
                    int num = Integer.parseInt(tvCommentsNum.getText().toString()) + 1;
                    tvCommentsNum.setText(String.valueOf(num));
                }
            }
        });
        model.getFocusResult().observe(this, result -> {
            if (!TextUtils.isEmpty(result))
            {
                tvFocus.setVisibility(View.GONE);
                Intent intent = new Intent(CommonConstant.EAM_BRD_ACTION_REQUEST_USERINFO);
                intent.putExtra("otherUserId", videoInfo.getUserId());
                mActivity.sendBroadcast(intent);
            }
        });
        model.getDeleteVideo().observe(this, result -> {
            // TODO: 2018/4/26 删除视频

            if (deleteListener != null)
            {
                deleteListener.onDelete(videoInfo);
            }

        });

        model.getShareVideo().observe(this, result -> {
            //分享视频成功
            Logger.t(TAG).d("分享视频成功");
        });

        model.getErrInfo().observe(this, errInfoBean -> {
            if (errInfoBean != null)
            {
                switch (errInfoBean.getInterfaceName())
                {
                    case Api.VIDEOC_LIKEVIDEO://点赞错误
                        Logger.t(TAG).d("点赞错误返回:" + errInfoBean.toString());
                        break;
                    case Api.VIDEOC_COMMENT_VIDEO://评论
                        if (errInfoBean.getErrorCode().equals(ErrorCodeTable.UNBOUND_MOBILE))
                        {
                            new CustomAlertDialog(mActivity)
                                    .builder()
                                    .setCancelable(true)
                                    .setMsg("当前未绑定手机号\n绑定后才可以操作哦\n")
                                    .setPositiveButton("去绑定", v ->
                                    {
                                        Intent intent = new Intent(mActivity, BindPhoneAct.class);
                                        mActivity.startActivity(intent);
                                    })
                                    .setNegativeButton("暂时不绑", v ->
                                    {
                                    }).show();
                        }
                        break;
                }
            }
        });
    }

    public void registerBroReceiver()
    {
        IntentFilter filter = new IntentFilter();
        filter.addAction(CommonConstant.EAM_BRD_ACTION_PLAY_VIDEO);
        filter.addAction(CommonConstant.EAM_BRD_ACTION_PAUSE_VIDEO);
        filter.addAction(CommonConstant.EAM_BRD_ACTION_FOCUS_SHOW);
        filter.addAction(CommonConstant.EAM_BRD_ACTION_FOCUS_HIDE);
        filter.addAction(CommonConstant.EAM_BRD_ACTION_RELEASE_VIDEO);
        filter.addAction(CommonConstant.REQUEST_LOGIN_CODE);
        mActivity.registerReceiver(receiver, filter);

        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver1, filter);
    }

    private void unRegisterBroReceiver()
    {
        if (receiver != null)
            mActivity.unregisterReceiver(receiver);

        if (receiver1 != null)
            LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver1);
    }

    BroadcastReceiver receiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            switch (intent.getAction())
            {
                case CommonConstant.EAM_BRD_ACTION_PLAY_VIDEO:
//                    if (isShow2User)
                    switchVideo(true);
                    break;
                case CommonConstant.EAM_BRD_ACTION_PAUSE_VIDEO:
                    switchVideo(false);
                    break;
                case CommonConstant.EAM_BRD_ACTION_FOCUS_SHOW:
                    String userId = intent.getStringExtra("userId");
                    if (videoInfo.getUserId().equals(userId))
                        tvFocus.setVisibility(View.VISIBLE);
                    break;
                case CommonConstant.EAM_BRD_ACTION_FOCUS_HIDE:
                    String userID = intent.getStringExtra("userId");
                    if (videoInfo.getUserId().equals(userID))
                        tvFocus.setVisibility(View.GONE);
                    break;
                case CommonConstant.EAM_BRD_ACTION_RELEASE_VIDEO:
                    String userId1 = intent.getStringExtra("userId");
                    if (videoInfo.getUserId().equals(userId1))
                    {
                        if (playVideo != null)
                        {
                            playVideo.onVideoPause();
                            playVideo.release();
                            isReleased = true;
                        }
                    }
                    break;
            }
        }
    };

    BroadcastReceiver receiver1 = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            switch (intent.getAction())
            {
                case CommonConstant.REQUEST_LOGIN_CODE:
                    if (TextUtils.equals(SharePreUtils.getUId(), videoInfo.getUserId()))
                    {
                        tvFocus.setVisibility(View.GONE);
                    }
                    break;

            }
        }
    };

    private void switchVideo(boolean play)
    {
        try
        {
            IMediaPlayer iMediaPlayers = playVideo.getGSYVideoManager().getMediaPlayer();
            if (iMediaPlayers != null)
            {
                if (play)
                {
                    if (isReleased)
                    {
                        setVideoPlay(videoUrl);
                        playVideo.startPlayLogic();
                        isReleased = false;
                    }
                    else
                    {
                        iMediaPlayers.start();
//                        playVideo.onVideoResume(false);
                    }

//                    iMediaPlayers.start();
                    Animation btnPlayAnim = AnimationUtils.loadAnimation(mActivity, R.anim.video_play_anim);
                    btnPlay.setVisibility(View.GONE);
                    btnPlay.setAnimation(btnPlayAnim);
                }
                else
                {
                    if (isPrepared)
//                        playVideo.onVideoPause();
                        iMediaPlayers.pause();
                    else
                    {
                        isNeedPause = true;
                    }
//                    iMediaPlayers.pause();
                    Animation btnPauseAnim = AnimationUtils.loadAnimation(mActivity, R.anim.video_pause_anim);
                    btnPlay.setVisibility(View.VISIBLE);
                    btnPlay.setAnimation(btnPauseAnim);
                }
            }
        } catch (IllegalStateException e)
        {
            e.printStackTrace();
            Logger.t(TAG).d("视频播放时失败:" + e.getMessage());
//            reSetVideo();

        } catch (Resources.NotFoundException e)
        {
            e.printStackTrace();
            Logger.t(TAG).d(e.getMessage());
        }
    }

    private void reSetVideo()
    {
        playVideo.setUp(videoUrl, false, null);
        playVideo.startPlayLogic();
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
    }

    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
        unRegisterBroReceiver();
        if (playVideo != null)
        {
            playVideo.release();
        }
        unbinder.unbind();
    }

    @OnClick({R.id.tvNickName, R.id.ivHead, R.id.tvFocus, R.id.rlLove, R.id.rlComments,
            R.id.rlShare, R.id.ll_bottom_lay, R.id.playVideo, R.id.deleteVideo})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.tvNickName:
            case R.id.ivHead:
                Intent intent = new Intent(CommonConstant.EAM_BRD_ACTION_VIDEO_CHANGE_PAGE);
                mActivity.sendBroadcast(intent);
                break;
            case R.id.tvFocus:
                if (CommonUtils.checkUserStateFromFragment(VideoPlayFragment.this, TAG))
                {
                    if (videoInfo != null)
                        model.focusPerson(videoInfo.getUserId());
                }
                break;
            case R.id.deleteVideo:
                new CustomAlertDialog(mActivity)
                        .builder()
                        .setMsg("是否删除该视频")
                        .setPositiveButton("是", new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                if (videoInfo != null)
                                    model.deleteVideo(videoInfo.getVideoId());
                            }
                        })
                        .setNegativeButton("否", new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {

                            }
                        })
                        .show();
                break;
            case R.id.rlComments:
                CommentListDialog commentListDialog = new CommentListDialog();
                Bundle bundle = new Bundle();
                bundle.putString("videoId", videoInfo.getVideoId());
                bundle.putString("videoSenderId", videoInfo.getUserId());
                commentListDialog.setArguments(bundle);
                commentListDialog.setCancelable(true);
                commentListDialog.setCommentEventActionListener(new CommentListDialog.CommentEventActionListener()
                {
                    @Override
                    public void onCommentSuccess()
                    {
                        int num = Integer.parseInt(tvCommentsNum.getText().toString()) + 1;
                        tvCommentsNum.setText(String.valueOf(num));
                    }

                    @Override
                    public void onCommentDelete()
                    {
                        int num = Integer.parseInt(tvCommentsNum.getText().toString()) - 1;
                        tvCommentsNum.setText(String.valueOf(num));
                    }
                });
                commentListDialog.show(getFragmentManager(), CommentListDialog.class.getSimpleName());
                break;
            case R.id.rlShare:
                showBottomSheet();
                break;
            case R.id.ll_bottom_lay:
                if (CommonUtils.checkUserStateFromFragment(VideoPlayFragment.this, TAG))
                {
                    NetUtil.checkIsBindMobile(new NetUtilListener()
                    {
                        @Override
                        public void onSuccess()
                        {
                            showCommentDialog();
                        }

                        @Override
                        public void onFail()
                        {
                            new CustomAlertDialog(mActivity)
                                    .builder()
                                    .setCancelable(true)
                                    .setMsg("当前未绑定手机号\n绑定后才可以操作哦\n")
                                    .setPositiveButton("去绑定", v ->
                                    {
                                        Intent intent = new Intent(mActivity, BindPhoneAct.class);
                                        mActivity.startActivity(intent);
                                    })
                                    .setNegativeButton("暂时不绑", v ->
                                    {
                                    }).show();
                        }
                    });
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode)
        {
            case CommonConstant.RESULT_CODE_OK:
                switch (requestCode)
                {
                    case CommonConstant.REQUEST_CODE_LOGIN:
                        //todo 绑定手机号
//                        showCommentDialog();
                        break;
                }
                break;
        }
    }

    @Override
    public void onStop()
    {
        super.onStop();
        switchVideo(false);
    }

    private void showCommentDialog()
    {
        dialog = new InputTextMsgDialog();
        dialog.setCancelable(true);
        dialog.setOnInputFinishedListener(inputContent ->
        {
            if (TextUtils.isEmpty(inputContent))
            {
                ToastUtils.showShort("请输入评论内容");
                return;
            }
            if (videoInfo != null)
                model.startCommentVideo(videoInfo.getVideoId(), inputContent);
        });
        dialog.show(mActivity.getFragmentManager(), InputTextMsgDialog.class.getSimpleName());
    }

    private void showBottomSheet()
    {

        if (bottomSheet == null)
        {
            bottomSheet = createBottomSheetView();
        }
        if (bottomSheetLayout.isSheetShowing())
        {
            bottomSheetLayout.dismissSheet();
            parentVerticalViewPager.setStopScroll(false);
        }
        else
        {
            if (sharesName.size() != 0)
            {
                bottomSheetLayout.showWithSheetView(bottomSheet);
                parentVerticalViewPager.setStopScroll(true);
            }
        }
    }

    private ArrayList<String> sharesName = new ArrayList<>();

    private SharesAdapter sharesAdapter;
    private View bottomSheet;

    private View createBottomSheetView()
    {
        ShareToFaceBean shareBean = new ShareToFaceBean();
        shareBean.setShareType(Platform.SHARE_WEBPAGE);
        String title = "小录段子";
        if (!TextUtils.isEmpty(videoInfo.getContent()))
        {
            title = videoInfo.getContent();
        }
        shareBean.setShareTitle(title);
//        shareBean.setShareTitleUrl(NetHelper.LIVE_SHARE_ADDRESS + SharePreUtils.getTlsName(mAct).substring(1));
        shareBean.setShareWeChatMomentsTitle(title);
        String shareUrl = String.format(Api.SHARE_URL + "?userid=%s&videoid=%s", SharePreUtils.getUId(), videoInfo.getVideoId());
        shareBean.setShareUrl(shareUrl);
        shareBean.setShareImgUrl(videoInfo.getThumbnails());
        shareBean.setShareContent("小录段子，流行风向标");
//        shareBean.setShareWeChatMomentsContent("越帅越优惠 越靓越实惠,看脸吃饭 【" + roomName + "】");
//        shareBean.setShareSinaContent("我的直播间是“" + roomName + "”,颜值高不高，直播才知道，赶快来给我送礼物吧！" + NetHelper.LIVE_SHARE_ADDRESS + SharePreUtils.getTlsName(mAct).substring(1));
//        shareBean.setShareAppImageUrl(NetHelper.LIVE_SHARE_PIC);
//        shareBean.setShareSite("看脸吃饭");
//        shareBean.setOpenSouse("liveShare");
//        shareBean.setRoomId(SharePreUtils.getId(mAct));
//        shareBean.setRoomName(SharePreUtils.getNicName(mAct));
//        shareBean.setShareSiteUrl(NetHelper.SERVER_SITE);
        shareBean.setShareListener(shareListener);


//        sharesName.add("新浪微博");
//        sharesName.add("看脸好友");
        sharesName.add("微信好友");
        sharesName.add("朋友圈");
//        sharesName.add("QQ好友");
//        sharesName.add("QQ空间");
        sharesName.add("举报");
        sharesName.add("存至相册");
        sharesName.add("复制链接");

        View view = LayoutInflater.from(mActivity).inflate(R.layout.pop_shares_list, (ViewGroup) mActivity.getWindow().getDecorView(), false);
        RecyclerView rvShares = view.findViewById(R.id.rvShares);
        sharesAdapter = new SharesAdapter(mActivity, sharesName);
        rvShares.setAdapter(sharesAdapter);
        sharesAdapter.setOnItemClickListener((vItem, shareKey) -> {
            switch (shareKey)
            {
                case "微信好友":
                    CommonUtils.shareWithApp(mActivity, "微信好友", shareBean);
                    break;
                case "朋友圈":
                    CommonUtils.shareWithApp(mActivity, "微信朋友圈", shareBean);
                    break;
                case "举报":
                    if (CommonUtils.checkUserStateFromFragment(VideoPlayFragment.this, TAG))
                    {
                        Intent intent = new Intent(getActivity(), ReportFoulsUserAct.class);
                        intent.putExtra("uId", videoInfo.getUserId());
                        startActivity(intent);
                    }
                    break;
                case "存至相册":
                    VideoUtils.saveVideoToMediaLib(mActivity,videoUrl);

/*                    String fileName = videoUrl.substring(
                            videoUrl.lastIndexOf("/") + 1, videoUrl.length()
                    );

//                    File sdcard = Environment.getExternalStorageDirectory();
                    File download = new File(
                            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath(),
                            "Camera"
                    );
                    if (!download.exists())
                    {
                        download.mkdir();
                    }

                    File saveFile = new File(download, fileName);
                    CdnHelper.getInstance().downloadFile(fileName, saveFile, new Callback()
                    {
                        @Override
                        public void onSuccess(JSONObject response)
                        {
                            //Log.i(TAG, "onSuccess " + response);
                            CommonUtils.insertIntoMediaStore(mActivity, true, saveFile.getPath(), 0);
                            mActivity.runOnUiThread(() -> {
                                ToastUtils.showShort("已保存至：" + saveFile.getPath());
                            });
                        }

                        @Override
                        public void onProcess(long len, int contentLength)
                        {
                            //TODO：下载进度
//                            int value = (int) (len * 100 / savefile.length());
                            //Log.i(TAG, "progress value is " + value);
//                            ToastUtils.showShort("下载中 "+value+"%");
                        }

                        @Override
                        public void onFail(JSONObject response)
                        {
                            //Log.i(TAG, "onFail " + response);
                        }
                    });*/
                    if (bottomSheetLayout.isSheetShowing())
                    {
                        bottomSheetLayout.dismissSheet();
                        parentVerticalViewPager.setStopScroll(false);
                    }
                    ToastUtils.showShort("下载中");
                    break;
                case "复制链接":
                    ClipboardManager cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                    // 将文本内容放到系统剪贴板里。
                    cm.setText(videoUrl);
                    ToastUtils.showShort("复制成功");
                    break;
                default:
                    CommonUtils.shareWithApp(mActivity, shareKey, shareBean);
            }
        });


        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 4)
        {
            @Override
            protected int getExtraLayoutSpace(RecyclerView.State state)
            {
                return 300;
            }
        };
        //设置布局管理器 , 将布局设置成纵向
//        LinearLayoutManager linerLayoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        rvShares.setLayoutManager(gridLayoutManager);

        //设置分隔线
        //mRecycleView.addItemDecoration(new DividerItemDecoration(this , DividerItemDecoration.VERTICAL_LIST));

        //设置增加或删除条目动画
        rvShares.setItemAnimator(new DefaultItemAnimator());

        return view;
    }

    PlatformActionListener shareListener = new PlatformActionListener()
    {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap)
        {
            mActivity.runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    model.shareVideo(videoInfo.getVideoId());
                    ToastUtils.showShort("分享成功");
                    int shareNum;
                    try
                    {
                        shareNum = Integer.parseInt(tvShareNum.getText().toString());
                        tvShareNum.setText(++shareNum + "");
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable)
        {
            mActivity.runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    ToastUtils.showShort("分享失败");
                }
            });

        }

        @Override
        public void onCancel(Platform platform, int i)
        {
            mActivity.runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    model.shareVideo(videoInfo.getVideoId());
                    ToastUtils.showShort("分享取消");
                    int shareNum;
                    try
                    {
                        shareNum = Integer.parseInt(tvShareNum.getText().toString());
                        tvShareNum.setText(++shareNum + "");
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            });
        }
    };


    public void setParentVerticalViewPager(VerticalViewPager parentVerticalViewPager)
    {
        this.parentVerticalViewPager = parentVerticalViewPager;
    }

    private IOnVideoDeleteListener deleteListener;

    public interface IOnVideoDeleteListener
    {
        void onDelete(Video video);
    }

    public void setOnVideoDeleteListener(IOnVideoDeleteListener listener)
    {
        this.deleteListener = listener;
    }

}